package com.py.inbound.service.impl;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;

import com.github.pagehelper.PageHelper;
import com.py.inbound.domain.*;
import com.py.inbound.mapper.OdSaleRejectedMapper;
import com.py.inbound.mapper.PyAttachmentMapper;
import com.py.inbound.mapper.PyInboundDetalisMapper;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.py.inbound.mapper.PyInboundMapper;
import com.py.inbound.service.IPyInboundService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import static com.ruoyi.common.core.utils.PageUtils.startPage;

/**
 * 入库管理Service业务层处理
 *
 * @author py
 * @date 2024-11-21
 */
@Service
public class PyInboundServiceImpl implements IPyInboundService {
    @Autowired
    private PyInboundMapper pyInboundMapper;
    @Autowired
    private PyInboundDetalisMapper pyInboundDetalisMapper;
    @Autowired
    private PyAttachmentMapper pyAttachmentMapper;
    @Autowired
    private OdSaleRejectedMapper odSaleRejectedMapper;
    @Autowired
    public RedisTemplate redisTemplate;

    /**
     * 入库排名
     */
    @Override
    public List<PyInbound> selectPyInboundRanking() {
        return pyInboundMapper.selectPyInboundRanking();
    }

    /**
     * 入库统计
     */
    @Override
    public StatisticsDate selectPyInboundStatistics(DateBeginEnd dateBeginEnd) {
        List<LocalDate> dateList = new ArrayList<>();
        long days = ChronoUnit.DAYS.between(dateBeginEnd.getBegin(), dateBeginEnd.getEnd());
        dateList.add(dateBeginEnd.getBegin());
//        System.out.println("当前时间：" + dateBeginEnd.getBegin());
        if (!dateBeginEnd.getBegin().equals(dateBeginEnd.getEnd())) {
            for (int i = 0; i < days; i++) {
                dateList.add(dateBeginEnd.getBegin().plusDays(i + 1));
            }
        }

        List<BigDecimal> priceList = new ArrayList<>(dateList.size());
        List<Integer> quantityList = new ArrayList<>(dateList.size());
        for (int i = 0; i < dateList.size(); i++) {
            priceList.add(BigDecimal.ZERO); // 初始化为零
            quantityList.add(0); // 初始化为零
        }

        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
//            System.out.println("beginTime:" + beginTime + "endTime:" + endTime);
            List<PyInbound> pyInbounds = pyInboundMapper.selectPyInboundStatistics(beginTime, endTime);
            BigDecimal totalPrice = BigDecimal.ZERO;
            Integer totalQuantity = 0;
            for (PyInbound pyInbound : pyInbounds) {
                totalPrice = totalPrice.add(pyInbound.getInboundPrice()); // 累加金额
                totalQuantity += pyInbound.getQuantityReceived(); // 累加数量
            }
            priceList.set(dateList.indexOf(date), totalPrice); // 设置对应日期的金额
            quantityList.set(dateList.indexOf(date), totalQuantity); // 设置对应日期的数量
        }

        return new StatisticsDate.Builder()
                .dateList(dateList)
                .price(priceList)
                .quantity(quantityList)
                .build();
    }

    /**
     * 查询入库管理
     *
     * @param inventoryId 入库管理主键
     * @return 入库管理
     */
    @Override
    public PyInbound selectPyInboundByInventoryId(Long inventoryId) {
        PyInbound pyInbound = pyInboundMapper.selectPyInboundByInventoryId(inventoryId);
        PyAttachment pyAttachment = new PyAttachment();
        pyAttachment.setOwnershipNumber(pyInbound.getInventoryNumber());
        pyInbound.setFileList(Collections.singletonList(pyAttachmentMapper.selectPyAttachmentList(pyAttachment)));
//        System.out.println("查询:" + pyInbound);
        return pyInbound;
    }

    /**
     * 查询入库管理列表
     *
     * @param pyInbound 入库管理
     * @return 入库管理
     */
    @Override
    public List<PyInbound> selectPyInboundList(PyInbound pyInbound) {
        return pyInboundMapper.selectPyInboundList(pyInbound);
    }

    /**
     * 新增入库管理
     *
     * @param pyInbound 入库管理
     * @return 结果
     */
    @Override
    @Transactional // 添加事务管理
    public int insertPyInbound(PyInbound pyInbound) {
        pyInbound.setCreator(SecurityUtils.getUserId().intValue());//制单人
        pyInbound.setCreationTime(new Date());
        pyInbound.setContactNumber(pyInbound.getContactPhone());
        List<Object> fileList = pyInbound.getFileList();
        System.out.println("fileList:" + fileList);
        if (fileList.size() > 0) {
            for (Object file : fileList) {
                if (file instanceof Map) {
                    Map<String, Object> fileMap = (Map<String, Object>) file;
                    Map<String, Object> response = (Map<String, Object>) fileMap.get("response");
                    Object ob = fileMap.get("size");
                    if (response != null) {
                        Map<String, Object> data = (Map<String, Object>) response.get("data");
                        if (data != null) {
                            String name = (String) data.get("name");
                            String url = (String) data.get("url");
                            System.out.println("Name: " + name);
                            System.out.println("URL: " + url);
                            PyAttachment pyAttachment = new PyAttachment();
                            if (pyInbound.getInventoryType() == 0) {
                                pyAttachment.setBusinessType("入库进货单");
                            } else if (pyInbound.getInventoryType() == 1) {
                                pyAttachment.setBusinessType("入库退货单");
                            }


                            pyAttachment.setOwnershipNumber(pyInbound.getInventoryNumber());
                            pyAttachment.setFileName(name);
                            pyAttachment.setSize(Long.parseLong(ob.toString()));
                            pyAttachment.setFilePath(url);
                            int i = pyAttachmentMapper.insertPyAttachment(pyAttachment);
                            System.out.println("附件:" + i);

                        }
                    }
                }
            }
        }
        int i = 0;
        i = pyInboundMapper.insertPyInbound(pyInbound);
        if (i > 0) {
            i = insertPyInboundDetalisList(pyInbound.getPyInboundDetalisList());

        }


        return i;
    }

    public int insertPyInboundDetalisList(List<PyInboundDetalis> pyInboundDetalis1) {
        Integer goodNum = 0;
        for (PyInboundDetalis p1 : pyInboundDetalis1) {
//            System.out.println("嘎嘎嘎:" + p1);
            // 假设 p1 是你的 PyInboundDetails 对象
            BigDecimal inboundPrice = null;
            if (p1.getInboundPrice() == null) {
                inboundPrice = p1.getSalePrice(); // 获取退货单入库价格
                p1.setInboundPrice(p1.getSalePrice());
            } else {
                inboundPrice = p1.getInboundPrice(); // 获取入库价格
            }
            if (p1.getQuantityReceived() == null) {
                p1.setQuantityReceived(p1.getAlreadyNum());
            }
            Integer quantityThisTime = p1.getQuantityThisTime(); // 获取本次入库数量
            // 将 Integer 转换为 BigDecimal
            BigDecimal quantityBigDecimal = BigDecimal.valueOf(quantityThisTime); // 转换为 BigDecimal
            // 进行乘法运算
            BigDecimal totalPrice = inboundPrice.multiply(quantityBigDecimal); // 计算总价格

            p1.setInboundAmount(totalPrice);
//            System.out.println("未入库数量:" + p1.getQuantityPending());
//            p1.setQuantityPending(p1.getQuantityThisTime());
            System.out.println("");
        }
        int add = pyInboundDetalisMapper.insertPyInboundDetalisList(pyInboundDetalis1);
        if (add > 0) {
            List<PyInboundDetalis> pyInboundDetalis2 = new ArrayList<>();
            for (PyInboundDetalis p2 : pyInboundDetalis1) {
                String lockKey = "lock:inventory:" + p2.getProductCode() + ":" + p2.getLocationCode();
                String lockValue = UUID.randomUUID().toString();
                Boolean isLock = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 30, TimeUnit.SECONDS);
                if (Boolean.TRUE.equals(isLock)) {
                    try {
                        WhInventory whInventory = new WhInventory();
                        whInventory.setPendingIn(p2.getQuantityThisTime());
                        whInventory.setProductCode(p2.getProductCode());
                        whInventory.setLocationCode(p2.getLocationCode());
                        int i = pyInboundDetalisMapper.updateupdateWhInventoryPendingIn(whInventory);
                        System.out.println("修改库存表未入库数量:" + i);
                        //修改库存失败说明没有,所以要新增一条
                        if (i == 0) {
                            System.out.println("进");
                            whInventory.setCurrentInventory(0);
//                    whInventory.setProductCode(p2.getProductCode());
                            System.out.println("id:" + p2.getWarehouseId());
                            String s = pyInboundDetalisMapper.SelectwarehouseCode(p2.getLocationCode());
                            System.out.println("编号:" + s);
                            whInventory.setWarehouseCode(pyInboundDetalisMapper.SelectwarehouseCode(p2.getLocationCode()));
                            whInventory.setPendingOut(0);
//                    whInventory.setLocationCode(p2.getLocationCode());
                            BigDecimal inboundPrice = null;
                            if (p2.getInboundPrice() == null) {
                                inboundPrice = p2.getSalePrice(); // 获取退货单入库价格
                                p2.setInboundPrice(p2.getSalePrice());
                            } else {
                                inboundPrice = p2.getInboundPrice(); // 获取入库价格
                            }
                            if (p2.getQuantityReceived() == null) {
                                p2.setQuantityReceived(p2.getAlreadyNum());
                            }
                            Integer quantityThisTime = p2.getQuantityThisTime(); // 获取本次入库数量
                            // 将 Integer 转换为 BigDecimal
                            BigDecimal quantityBigDecimal = BigDecimal.valueOf(quantityThisTime); // 转换为 BigDecimal
                            // 进行乘法运算
                            BigDecimal totalPrice = inboundPrice.multiply(quantityBigDecimal); // 计算总价格
                            whInventory.setInventoryValue(totalPrice);
                            whInventory.setAvailableInventoryValue(totalPrice);
                            whInventory.setInventoryUpperLimit(100);
                            whInventory.setInventoryLowerLimit(10);
                            pyInboundDetalisMapper.insertWhInventory(whInventory);
                        }

                    } finally {
                        // 释放锁
                        if (lockValue.equals(redisTemplate.opsForValue().get(lockKey))) {
                            redisTemplate.delete(lockKey);
                        }
                    }
                } else {
                    System.out.println("库存更新操作正在进行中，请稍后再试。");
                }
            }
        }
        return add;
    }

    @Override
    @Transactional(rollbackFor = Exception.class) // 添加事务管理
    public int updateStatus(PyInbound pyInbound) {
        System.out.println("状态:" + pyInbound.getStatus());
        if (pyInbound.getStatus() == 2) {
            // 使用分布式锁
            String lockKey = "lock:inventory:status:" + pyInbound.getInventoryNumber();
            String lockValue = UUID.randomUUID().toString();
            Boolean isLock = redisTemplate.opsForValue().setIfAbsent(lockKey, lockValue, 30, TimeUnit.SECONDS);
            if (Boolean.TRUE.equals(isLock)) {
                try {
                    shrk(pyInbound);
                } finally {
                    // 释放锁
                    if (lockValue.equals(redisTemplate.opsForValue().get(lockKey))) {
                        redisTemplate.delete(lockKey);
                    }
                }
            } else {
                System.out.println("审核操作正在进行中，请稍后再试。");
            }

        }

        return pyInboundMapper.updateStatus(pyInbound);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class) // 添加事务管理
    public void shrk(PyInbound pyInbound) {
        System.out.println("入库类型:::" + pyInbound.getInventoryType());
        System.out.println("单号:::" + pyInbound.getInventoryNumber());
        int rksl = 0;
        List<PyInboundDetalis> pyInboundDetalis = pyInboundDetalisMapper.selectAllPyInboundDetalisBycode(pyInbound.getInventoryNumber());
        System.out.println("pyInboundDetalis::" + pyInboundDetalis);

        //        // 检查 pyInboundDetalis 是否为 null 或空
        //        if (pyInboundDetalis == null || pyInboundDetalis.isEmpty()) {
        //            System.out.println("没有找到入库明细，无法进行入库操作。");
        //            return; // 结束方法
        //        }

        for (PyInboundDetalis p : pyInboundDetalis) {
            //            if (p == null) {
            //                System.out.println("入库明细项为 null，跳过该项。");
            //                continue; // 跳过 null 项
            //            }

            System.out.println(p);
            Integer quantityThisTime = p.getQuantityThisTime(); // 本次入库数量
            System.out.println("本次入库数量:" + quantityThisTime);
            Integer quantityReceived = p.getQuantityReceived(); // 已入库数量
            System.out.println("已入库数量:" + quantityReceived);

            // 确保 quantityReceived 和 quantityThisTime 都不为 null
            rksl += (quantityReceived != null ? quantityReceived : 0) + (quantityThisTime != null ? quantityThisTime : 0);
            // 设置已入库数量
            p.setQuantityReceived((quantityReceived != null ? quantityReceived : 0) + (quantityThisTime != null ? quantityThisTime : 0));

            //            // 检查 d 是否为 null
            //            if (d == null) {
            //                System.out.println("未找到相关的采购明细，跳过该项。");
            //                continue; // 跳过该项
            //            }
            if (pyInbound.getInventoryType() == 0) {
                // 计算未入库
                OdPurchaseDetails d = pyInboundMapper.selectNumberOdDetalis(pyInbound.getRelatedNumber(), p.getProductCode());

                Integer productNum = d.getProductNum() != null ? d.getProductNum() : 0;
                Integer rejectedNum = p.getQuantityReceived() != null ? p.getQuantityReceived() : 0;
                Integer alreadyNum = d.getAlreadyNum() != null ? d.getAlreadyNum() : 0;

                // 计算未入库数量
                p.setQuantityPending(productNum - rejectedNum - alreadyNum);
            } else if (pyInbound.getInventoryType() == 1) {

                OdSaleRejectedDetails s = odSaleRejectedMapper.selectNumberSaleRejectedDetails(pyInbound.getRelatedNumber(), p.getProductCode());
                p.setQuantityPending(s.getRejectedNum() - p.getQuantityReceived());

            }


            // 更新已入库数量和未入库数量
            int i = pyInboundDetalisMapper.updatequantityReceivedNumber(p);
            if (pyInbound.getInventoryType() == 0) {
                // 更新进货订单已入库数量
                int i1 = pyInboundDetalisMapper.updatealreadyNumOdDetalis(p);
            }

            BigDecimal price = p.getInboundPrice(); // 获取单价
            BigDecimal quantityBigDecimal = new BigDecimal(quantityThisTime != null ? quantityThisTime : 0);

            // 进行乘法运算，确保乘以价格时不为 null
            BigDecimal totalPrice = quantityBigDecimal.multiply(price != null ? price : BigDecimal.ZERO);

            // 更新库存信息
            WhInventory whInventory = new WhInventory();
            whInventory.setCurrentInventory(p.getQuantityThisTime());
            whInventory.setLocationCode(p.getLocationCode());
            whInventory.setProductCode(p.getProductCode());
            whInventory.setInventoryValue(totalPrice);
            whInventory.setAvailableInventoryValue(totalPrice);
            whInventory.setPendingIn(p.getQuantityThisTime());

            // 更新库存数量
            pyInboundDetalisMapper.updateWhInventoryKcNumber(whInventory);
            int i2 = pyInboundDetalisMapper.updateupdateWhInventoryPendingInJian(whInventory);
            System.out.println("库存待入库修改:" + i2);
        }

        if (pyInbound.getInventoryType() == 0) {
            Integer goodNum = pyInboundDetalisMapper.selectGoodNum(pyInbound.getRelatedNumber());
            System.out.println("goodNum："+goodNum);
            System.out.println("rksl："+rksl);
            if (rksl == goodNum) {
                System.out.println("rksl:" + rksl);
                System.out.println("goodNum:" + goodNum);
                OdPurchaseOrder odPurchaseOrder = new OdPurchaseOrder();
                odPurchaseOrder.setPhState("4"); // 已完成
                odPurchaseOrder.setPhCode(pyInboundDetalis.get(0).getPhCode());
                pyInboundDetalisMapper.updateaStateOdDetalis(odPurchaseOrder);
            } else if (rksl < goodNum) {
                OdPurchaseOrder odPurchaseOrder1 = new OdPurchaseOrder();
                odPurchaseOrder1.setPhState("3"); // 部分入库
                odPurchaseOrder1.setPhCode(pyInboundDetalis.get(0).getPhCode());
                pyInboundDetalisMapper.updateaStateOdDetalis(odPurchaseOrder1);
            }
        } else if (pyInbound.getInventoryType() == 1) {
//            System.out.println("进入");
            Integer goodNum = pyInboundDetalisMapper.selectGoodNumTH(pyInbound.getRelatedNumber());
            System.out.println("rksl:" + rksl);
            System.out.println("goodNum:" + goodNum);
            OdSaleRejected odSaleRejected = new OdSaleRejected();
            odSaleRejected.setSrCode(pyInboundDetalis.get(0).getPhCode());
            if (rksl == goodNum) {
                odSaleRejected.setSrState("4"); // 已完成
                pyInboundDetalisMapper.updateaStateOdSaleRejected(odSaleRejected);
            } else if (rksl < goodNum) {
                odSaleRejected.setSrState("3"); // 部分入库
                pyInboundDetalisMapper.updateaStateOdSaleRejected(odSaleRejected);
            }
        }
    }

    /**
     * 修改入库管理
     *
     * @param pyInbound 入库管理
     * @return 结果
     */
    @Override
    @Transactional
    public int updatePyInbound(PyInbound pyInbound) {
        pyInbound.setUpdateTime(DateUtils.getNowDate());
        pyAttachmentMapper.deletePyAttachmentByOwnershipNumber(pyInbound.getInventoryNumber());
        List<Object> fileList = pyInbound.getFileList();
        System.out.println("列表:" + fileList);
        System.out.println("列表02:" + pyInbound);
        if (fileList.size() > 0) {
            System.out.println("进来了11111111111111");
            for (Object file : fileList) {
                if (file instanceof Map) {
                    Map<String, Object> fileMap = (Map<String, Object>) file;
                    String name = (String) fileMap.get("name");
                    String url = (String) fileMap.get("url");
                    Object size = fileMap.get("size");
                    // 如果 name 和 url 不为空，直接使用
                    if (name != null && url != null) {
                        System.out.println("Name: " + name);
                        System.out.println("URL: " + url);
                        PyAttachment pyAttachment = new PyAttachment();
                        if (pyInbound.getInventoryType() == 0) {
                            pyAttachment.setBusinessType("入库进货单");
                        } else if (pyInbound.getInventoryType() == 1) {
                            pyAttachment.setBusinessType("入库退货单");
                        }
                        pyAttachment.setOwnershipNumber(pyInbound.getInventoryNumber());
                        pyAttachment.setFileName(name);
                        pyAttachment.setSize(Long.parseLong(size.toString()));
                        pyAttachment.setFilePath(url);
                        pyAttachmentMapper.insertPyAttachment(pyAttachment);
                        continue;
                    }
                    // 如果 name 或 url 为空，尝试从 response 中获取
                    Map<String, Object> response = (Map<String, Object>) fileMap.get("response");
                    if (response != null) {
                        Map<String, Object> data = (Map<String, Object>) response.get("data");
                        if (data != null) {
                            name = (String) data.get("name");
                            url = (String) data.get("url");
                            if (name != null && url != null) {
                                System.out.println("Name: " + name);
                                System.out.println("URL: " + url);
                                PyAttachment pyAttachment = new PyAttachment();
                                if (pyInbound.getInventoryType() == 0) {
                                    pyAttachment.setBusinessType("入库进货单");
                                } else if (pyInbound.getInventoryType() == 1) {
                                    pyAttachment.setBusinessType("入库退货单");
                                }
                                pyAttachment.setOwnershipNumber(pyInbound.getInventoryNumber());
                                pyAttachment.setFileName(name);
                                pyAttachment.setSize(Long.parseLong(size.toString()));
                                pyAttachment.setFilePath(url);
                                pyAttachmentMapper.insertPyAttachment(pyAttachment);
                            }
                        }
                    }
                }
            }
        }
        return pyInboundMapper.updatePyInbound(pyInbound);
    }

    /**
     * 批量删除入库管理
     *
     * @param inventoryIds 需要删除的入库管理主键
     * @return 结果
     */
    @Override
    public int deletePyInboundByInventoryIds(Integer[] inventoryIds) {
        String[] values = new String[inventoryIds.length];
        int index = 0;
        for (Integer inventoryId : inventoryIds) {
            String order = pyInboundMapper.selectinventoryNumber(inventoryId);
//            System.out.println("order:" + order);
            // 假设你想将每个订单的某个属性（例如 phCode）添加到 values 数组中
            values[index++] = order;
        }
        System.out.println("va:" + values.toString());
        pyInboundDetalisMapper.deletePyInboundDetalisByinventoryNumber(values);
//        return odPurchaseOrderMapper.deleteOdPurchaseOrderByPhIds(phIds);
        return pyInboundMapper.deletePyInboundByInventoryIds(inventoryIds);
    }

    /**
     * 删除入库管理信息
     *
     * @param inventoryId 入库管理主键
     * @return 结果
     */
    @Override
    public int deletePyInboundByInventoryId(Long inventoryId) {
        return pyInboundMapper.deletePyInboundByInventoryId(inventoryId);
    }

    /**
     * 进货部门
     *
     * @return
     */
    @Override
    public List<SysDept> selectAllSysDept() {
        return pyInboundMapper.selectAllSysDept();
    }

    /**
     * 根据父Id 查询部门
     */
    @Override
    public List<SysDept> selectAllSysDeptByParentId(Long deptid) {
        return pyInboundMapper.selectAllSysDeptByParentId(deptid);
    }

    @Override
    public List<SysUser> selectAllSysUserByParentId(Long deptid) {
        return pyInboundMapper.selectAllSysUserByParentId(deptid);
    }

    @Override
    public List<PySuppliers> selectAllPySuppliers() {
        return pyInboundMapper.selectAllPySuppliers();
    }

    @Override
    public List<BsWarehouse> selectAllBsWarehouse() {
        return pyInboundMapper.selectAllBsWarehouse();
    }

    @Override
    public PySuppliers selectSuppliersByid(Long supplierId) {
        return pyInboundMapper.selectSuppliersByid(supplierId);
    }

    @Override
    public List<OdPurchaseOrder> selectAllOdPurchaseOrder(OdPurchaseOrder odPurchaseOrder) {
        return pyInboundMapper.selectAllOdPurchaseOrder(odPurchaseOrder);
    }

    @Override
    public List<OdPurchaseDetails> selectAllOdPurchaseDetails(OdPurchaseDetails odPurchaseDetails) {
        List<OdPurchaseDetails> odPurchaseDetails1 = pyInboundMapper.selectAllOdPurchaseDetails(odPurchaseDetails);
//        if (odPurchaseDetails1 == null) {
//            odPurchaseDetails1 = new ArrayList<>(); // 避免 null
//        }
//        odPurchaseDetails1.forEach(s -> System.out.println("打印:" + odPurchaseDetails1));
        for (OdPurchaseDetails od : odPurchaseDetails1) {
//            System.out.println("萨达:" + od);
            // 如果已入库数量=0,未入库数量就=货品数量
            if (od.getAlreadyNum() == null || od.getAlreadyNum() == 0) {
                od.setNotStocked(od.getProductNum());
            } else {
//                System.out.println("od.getProductCode():" + od.getProductCode());
//                System.out.println("od.getPhDetailsId():" + od.getPhDetailsId());
                PyInboundDetalis pyInboundDetalis = new PyInboundDetalis();
                pyInboundDetalis.setProductCode(od.getProductCode());
                pyInboundDetalis.setPhDetailsId(od.getPhDetailsId());
                pyInboundDetalis.setPhCode(od.getPhCode());
//                System.out.println("pyInboundDetalis计算:" + pyInboundDetalis);
                List<Integer> receivedList = pyInboundDetalisMapper.selectquantityReceived(pyInboundDetalis);
                int receivedTotal = 0; // 用于存储总的已接收数量

                if (receivedList != null && !receivedList.isEmpty()) {
                    // 汇总数量
                    receivedTotal = receivedList.stream().mapToInt(Integer::intValue).sum();
                }
//                System.out.println("od.getPhDetailsId():" + od.getPhDetailsId() + "getRejectedNum:" + od.getRejectedNum());
                od.setNotStocked(od.getProductNum() - od.getRejectedNum() - receivedTotal);
//                System.out.println("货品编号:" + od.getProductName() + "货品未入库" + od.getNotStocked());
//                StackOverflowError
                // 计算未入库数量: 未入库数量 = 进货数量 - 退货数量 - 已接收数量
//                int rejectedNum = od.getRejectedNum() != null ? od.getRejectedNum() : 0; // 处理可能的 null


            }
        }

        return odPurchaseDetails1;
    }

    @Override
    public List<WhInventory> selectWhInventoryByCode(WhInventory whInventory) {
        return pyInboundMapper.selectWhInventoryByCode(whInventory);
    }

    @Override
    public List<BsWhLocation> selectAllBsWhLocation(Integer wid) {
        return pyInboundMapper.selectAllBsWhLocation(wid);
    }


    @Override
    public List<OdInRejected> selectAllOdInRejected(OdInRejected odInRejected) {
        return pyInboundMapper.selectAllOdInRejected(odInRejected);
    }

    @Override
    public List<OdRejectedDetails> selectOdRejectedDetails(OdRejectedDetails odRejectedDetails) {
        return pyInboundMapper.selectOdRejectedDetails(odRejectedDetails);
    }

    @Override
    public List<PyInbound> inPyInboundLS(PyInbound pyInbound) {

        List<PyInbound> pyInbounds = pyInboundMapper.inPyInboundLS(pyInbound);
//        System.out.println("大打野:" + pyInbounds);
        return pyInbounds;
    }

    @Override
    public PyInbound inTotal() {
        return pyInboundMapper.inTotal();
    }


}
